<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <h1>{{this.$store.state.num}}</h1>
        <button @click="add">同步 加一</button>
        <button @click="asyncAdd">异步 加</button>
    </div>
</body>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="./node_modules/vuex/dist/vuex.js"></script>
<script>
    //Vuex对象
    //a,1 Vuex.Store 对象
    let store = new Vuex.Store({
        //state 仓库数据
        state:{
            num:999
        },
        //修改值
        //触发mutations
        mutations:{
            //加操作
            jia:function(state,res){
                state.num+=res; //999+res
            }
        },
        //actions 中可以允许有异步操作
        actions:{
            asyncAdd:function(context){
                //先去后台请求数据
                setTimeout(function(){
                    let res = 10; //假设10是网络请求返回的树
                    context.commit("jia",res)
                },1000)
            }
        }
    })
    //a,2 作为配置,传到Vue实例中
    //this.$store 访问到仓库
    let vm = new Vue({
        el:"#app",
        store:store,
        methods:{
            //同步加
            add:function(){
                //
                this.$store.commit("jia",1);
            },
            //异步
            asyncAdd:function(){
                this.$store.dispatch("asyncAdd")
            }
        }
    })
</script>
</html>